package com.gs.wechatdemo.signalr;

import android.os.Handler;

import com.gs.wechatdemo.util.OKHttpUtil;

public class SignalRUtil {
    private static volatile SignalRUtil instance;

    private SignalRChannel signalRChannel;
    private boolean isRunning = true;
    private Thread thread;
    private final static String HUB_URL = OKHttpUtil.NET_URL + "/api/broadcastHub";

    public static SignalRUtil getInstance() {
        if (instance == null) {
            synchronized (SignalRUtil.class) {
                if (instance == null) {
                    instance = new SignalRUtil();
                }
            }
        }
        return instance;
    }


    public void startConnect(Handler handler) {
        if (signalRChannel == null) {
            signalRChannel = new SignalRChannel(HUB_URL, handler);
            signalRChannel.startConnect();
        }
        if (thread == null) {
            thread = new Thread(runnableSend);
            thread.start();
        }
    }

    private Runnable runnableSend = new Runnable() {
        @Override
        public void run() {
            while (isRunning) {
                // 刷新连接状态
                if (signalRChannel != null && signalRChannel.isConnected() != true) {
                    signalRChannel.startSync();
                }
                signalRChannel.sendFailMsg();
                try {
                    Thread.sleep(4000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    };

    public void stopConnect() {
        if (signalRChannel != null) {
            signalRChannel.stopConnect();
            signalRChannel = null;
        }
        if (thread != null) {
            isRunning = false;
            thread.interrupt();
        }
    }

    public void send(String method, Object... message) {
        signalRChannel.send(method, message);
    }
}
